import socket
import types
import time
import urllib
import urllib.request


class Login:
    """初始化"""

    def __init__(self):
        self.username = ''
        self.password = ''
        # 网段
        self.ip_pre = '192.168'
        # 登录时长
        self.overtime = 720
        # 检测间隔时间，单位为秒
        self.every = 10

    def login(self):
        print(self.getCuttentTime() + "正在尝试认证QLSC_STU无线网络")
        ip = self.getIP()
        data = {
            "username": self.username,
            "password": self.password,
            "ClientIP": self.getIP(),
            "StartTime": self.getNowTime()
        }
        # 消息头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36',
            'Host': '192.168.8.10',
            'Origin': 'http://192.168.8.10',
            'Referer': 'http://192.168.8.10/portal/index_default.jsp?Language=Chinese'
        }
        post_data = urllib.parse.urlencode(data)
        login_url = "http://192.168.8.10/portal/login.jsp?Flag=0"
        request = urllib.request.Request(login_url, post_data, headers)
        response = urllib.request.urlopen(request)
        result = response.read().decode('utf-8')
        self.getLoginResult(result)

        # 获取本机无线IP
    def getIP(self):
        local_ip = socket.gethostbyname(socket.gethostname())
        if self.ip_pre in str(local_ip):
            return str(local_ip)
        ip_lists = socket.gethostbyname_ex(socket.gethostname())

        for ip_list in ip_lists:
            if isinstance(ip_list, list):
                for i in ip_list:
                    if self.ip_pre in str(i):
                        return str(i)
            elif isinstance(ip_list, str):
                if self.ip_pre in ip_list:
                    return ip_list
